package com.eastmelon.udp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author Administrator
 *模拟的简易的聊天系统
 */
public class Chating {
	public static void main(String[] args) throws Exception {
		DatagramSocket rece=new DatagramSocket(1001);
		DatagramSocket send=new DatagramSocket();
		new Thread(new Rece(rece)){}.start();
		new Thread(new Send(send)){}.start();
	}

}

class Rece implements Runnable {
	private DatagramSocket ds;
	public Rece (DatagramSocket ds){
		this.ds=ds;
	}
	public void run() {
		try {
			while (true) {
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				ds.receive(dp);
				String mes=new String(dp.getData(),0,dp.getLength());
				System.out.println(dp.getAddress().getHostAddress()+".."+mes);
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}
}

class Send implements Runnable {
	private DatagramSocket ds;
	public Send (DatagramSocket ds){
		this.ds=ds;
	}
	public void run() {
		try {
			while (true) {
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
				String line = null;
				while ((line = br.readLine()) != null) {
					byte[] buf = line.getBytes();
					DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 1001);
					ds.send(dp);
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		} 
	};
}
